<template>
  <div class="clothingList">
    <!-- <div class="backBox">
      <div class="leftBox" @click="onClickLeft">
        <van-icon name="arrow-left" class="backIcon" />
        <span>返回</span>
      </div>
      <div class="title">开始任务</div>
    </div> -->
    <CommonHeader @loginOut="loginOut" :title="'挂片模式'" :userData="userData">
      <template v-slot>
        <div class="linkItem" @click="toClothingOrder">
          <span>制衣单</span>
        </div>
      </template>
    </CommonHeader>
    <div class="content">
      <div class="title">
        <div class="totlaNum">共 <span style="font-size:20px;">{{totlaNum}}</span> 件</div>
        <img src="@/assets/img/rightSquare.png" alt="">
        <h3>当前推荐挂片</h3>
        <div class="statusBox">
          <img v-if="statusSocket" src="@/assets/img/链接@2x.png" alt="">
          <img v-else src="@/assets/img/断开@2x.png" alt="">
          <span :class="{'textActive':statusSocket}">{{statusText}}</span>
        </div>
      </div>
      <div class="itemBox">
        <!--  OrderData.OrderDetail -->
        <div class="item" v-for="(v,k) in OrderData.OrderDetail" :key="k">
          <div class="dotBox">
            <span class="dot" :class="{'active':item.activeFlag}" v-for="(item,index) in v.dotList" :key="index"></span>
          </div>
          <div style="margin-top: 15px;" :class="{'msgBoxActiveRed':v.RedBorder}">
            <div class="msgBox" :class="{'msgBoxActive':v.Border,'msgFive':OrderData.OrderDetail.length>=5}">
              <van-image class="vanImg" width="130" height="230" radius="5" :src="v.ImagePath" alt="" />
              <div class="msg" @click="changeSize(v)">
                <div class="msgItem">
                  <span v-show="OrderData.OrderDetail.length<5">生产单号</span>
                  <span>{{v.BillNo}}</span>
                </div>
                <div class="msgItem">
                  <span>款号</span>
                  <span>{{v.StyleNo?v.StyleNo:'-'}}</span>
                </div>
                <div class="msgItem">
                  <span>颜色</span>
                  <span>{{v.Color}}</span>
                </div>
                <div class="msgItem">
                  <span>尺码</span>
                  <span>{{v.SizeName?v.SizeName:'-'}}</span>
                </div>
                <div class="msgItem">
                  <span>目标产量</span>
                  <span>{{v.DestQty}}</span>
                </div>
                <div class="msgItem">
                  <span>已投数量</span>
                  <span>{{v.InvestedQty}}</span>
                </div>
              </div>
              <div class="btnBox">
                <van-button class="btn" type="primary" color="#FEEA27" @click="downLine(v,k)">下线</van-button>
              </div>
               <!-- 首站衣架 -->
              <div class="firstStationQty">首站衣架{{v.FirstStationQty?v.FirstStationQty:0}}个</div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <!-- dialog -->
    <van-dialog :before-close="inputCancel" width="600px" title="切换尺码" confirm-button-color="#135BC3" v-model="show" show-cancel-button>
      <div class="dialogBox">
        <div :class="{'questionItemActive':v==sizeName}" class="questionItem" @click="selectClick(v)" v-for="(v,k) in sizeList" :key="k">
          <span>{{v}}</span>
        </div>
        <template v-if="(sizeList.length)%3 > 0">
          <div class="questionItemAfter" v-for="(v,k) in (3 - (sizeList.length)%3)" :key="k+100"></div>
        </template>
      </div>
    </van-dialog>
  </div>
</template>

<script>
import CommonHeader  from '@/components/CommonHeader'
import { Dialog,Toast } from 'vant'
import { OffLineApi,defaultAxios,getSizeList,setSize } from '@/api/loginApi'
export default {
  data() {
    return {
      OrderData: {
        OrderDetail:[]
      },
      userData:{},
      isLoginOut: false,
      totlaNum:0,
      statusText:'已连接',
      statusSocket: false,
      show: false,
      sizeList:[],
      sizeName:'',
      selectData:{},
      // websocket 增加心跳检测
      lockReconnect:false, //避免重复连接let ws;
      // 心跳检测
      heartCheck:{    
        timeout: 60000,    
        timer: null,    
        serverTimer: null,       
      }
    }
  },
  mounted(){
    if(sessionStorage.getItem('userData')){
      this.userData = JSON.parse(sessionStorage.getItem('userData'))
      this.initWebSocket()
    }
  },
  methods:{
    toClothingOrder(){
      this.$router.push('/hanger/clothingList')
    },
    reset(){        
      clearTimeout(this.heartCheck.timer);        
      clearTimeout(this.heartCheck.serverTimer)
      this.start();    
    }, 
    start(){        
      let ts = this;        
      this.heartCheck.timer = setTimeout(function(){            
        ts.websock.send('OK');            
        ts.heartCheck.serverTimer = setTimeout(function(){                
          ts.websock.onclose();            
        }, ts.heartCheck.timeout)       
      }, this.heartCheck.timeout)    
    },
    changeSize(item){
      this.show = true
      this.selectData = item
      this.sizeName = item.SizeName
      getSizeList({MONo:item.MONo}).then(res =>{
        this.sizeList = res.data
      })
    },
    selectClick(v){
      this.sizeName = v
    },
    // 弹框取消事件
    inputCancel (action,done){
      if(action == 'confirm'){
        setSize({matchID:this.selectData.MatchID,sizeName: this.sizeName}).then(res =>{
          if(res.data.success){
            this.selectData.SizeName = this.sizeName
            Toast(res.data.message)
            done()
          }else{
            done(false)
          }
        })
      }else{
       done()
      } 
    },
    initWebSocket(){//初始化websocket
      let reuestAddress = localStorage.getItem('requestAddress')?JSON.parse(localStorage.getItem('requestAddress')):{}
      const wsuri = 'ws://'+reuestAddress.wsAddress;
      this.websock = new WebSocket(wsuri);//这里面的this都指向vue
      this.websock.onopen = this.websocketopen;
      this.websock.onmessage = this.websocketonmessage;
      this.websock.onclose = this.websocketclose;
      this.websock.onerror = this.websocketerror;
    },
    websocketopen(){//打开
      this.start()
      console.log("WebSocket连接成功")
      this.statusSocket = true
      this.statusText = '已连接'
      // if(this.socketTimer){
      //   clearInterval(this.socketTimer)
      // }
      let params = JSON.stringify({
        LineNumber: this.userData.lineNumber,
        StationNum: this.userData.stationNum,
        JobNumber: this.userData.jobNumber,
        GroupCode: this.userData.groupCode,
        // LineType:'线内'
      })
      console.log(params)
      this.websock.send(params);
    },
    websocketonmessage(e){ //数据接收
    // 收到消息的时候重置倒计时        
      this.reset();
      if(e.data != 'OK'){
        console.log(JSON.parse(e.data))
        this.OrderData = JSON.parse(e.data)
        this.totlaNum = 0
        this.OrderData.OrderDetail.forEach((item,index) =>{
          this.totlaNum += item.InvestedQty
          this.$set(item,'dotList',[])
          for(var i=0;i<item.MatchNum;i++){
            item.dotList.push({
              num: item.MatchNum,
              activeFlag: item.MatchedNum>i
            })
          }
        })
        // this.OrderData.OrderDetail.push(this.OrderData.OrderDetail[0])
        // var arr = new Array();
        // for(var i=0;i<100;i++){
        //   arr.push(i);
        // }
        console.log(this.OrderData.OrderDetail)
        // 默认选中第一个
      }
    },
    websocketclose(){ //关闭
      console.log("WebSocket关闭");
      // Toast("WebSocket关闭,正在尝试重新连接")
      if(!this.isLoginOut){
        this.statusSocket = false
        this.statusText = '已断开'
          this.reconnect();
        }
      // if(!this.isLoginOut){
      //   Toast("WebSocket关闭，正在尝试重新连接")
      //   this.statusSocket = false
      //   this.statusText = '已断开'
      //   defaultAxios().then(res =>{
          
      //   })
      // }
      //   console.log("WebSocket关闭,正在尝试重新连接");
      // // this.initWebSocket()
      // clearInterval(this.socketTimer)
      // this.socketTimer = setInterval(() =>{
      //     this.initWebSocket()
      // },5000)
    },
    websocketerror(){ //失败
      Toast("WebSocket连接失败,正在尝试重新连接")
      console.log("WebSocket连接失败");
      if(!this.isLoginOut){
        this.statusSocket = false
        this.statusText = '已断开'
        this.reconnect();
      }
      // Toast("WebSocket连接失败")
      // console.log("WebSocket连接失败");
      // if(!this.isLoginOut){
      //   Toast("WebSocket连接失败，正在尝试重新连接")
      //   this.statusSocket = false
      //   this.statusText = '已断开'
      //   defaultAxios().then(res =>{
          
      //   })
      // }
      // clearInterval(this.socketTimer)
      // this.socketTimer = setInterval(() =>{
      //     this.initWebSocket()
      // },5000)
    },
    reconnect() {    
      if(this.lockReconnect) return;    
        this.lockReconnect = true;    
        //没连接上会一直重连，设置延迟避免请求过多    
      setTimeout(() =>{
        defaultAxios().then(res =>{
          })
          this.initWebSocket()
        this.lockReconnect = false
      },5000)
    },
    onClickLeft(){
      this.$router.go(-1)
    },
    downLine(v,index){
      Dialog.confirm({
        title: '提示',
        message: '确认要下线吗?',
        confirmButtonColor: '#1989fa',
      })
        .then(() => {
          let params = {
            matchID: v.MatchID
          }
          OffLineApi(params).then(res =>{
            if(res.data.code == 0){
              this.OrderData.OrderDetail.splice(index,1)
              Toast('操作成功')
            }
          })
        })
        .catch(() => {
          // on cancel
        });
    },
    loginOut() {
      this.isLoginOut = true
      this.websock.close()
      clearInterval(this.socketTimer)
    }
  },
  components:{
    CommonHeader
  },
  // 离开该层时执行，划重点了！！！
  destroyed: function () {
    // 离开路由之后断开websocket连接
    this.websock.close()
    clearInterval(this.socketTimer)
  },
}
</script>

<style lang="less" scoped>
  .clothingList{
    background: #E7F3F9;
    height: 100%;
    display: flex;
    flex-direction: column;
    /deep/ .van-dialog__header{
      font-size: 20px;
    }
    /deep/ .van-dialog__cancel, /deep/ .van-dialog__confirm{
      font-size: 19px;
    }
    .linkItem{
      display: flex;
      align-items: center;
      justify-content: center;
      position: relative;
      width: 110px;
      .backTo{
        margin-left: 10px;
      }
      &::before{
        content: '';
        position: absolute;
        top: 0;
        right: 0;
        bottom: 0;
        left: 0;
        transform: skewX(15deg);
        border-left: 1px solid #eee;
      }
    }
    .dialogBox{
      display: flex;
      flex-wrap: wrap;
      justify-content: space-between;
      padding: 25px 20px 15px 20px;
      overflow: scroll;
      max-height: 380px;
      .questionItem{
        background: #E7EFF9;
        padding: 20px 10px;
        border-radius: 8px;
        width: 28%;
        margin-bottom: 15px;
        text-align: center;
        font-size: 18px;
      }
      .questionItemActive{
        color: #fff;
        background: #F56C6C;
      }
      .questionItemAfter{
        content:' ';
        width: 28%;
        padding: 10px;
      }
    }
    .backBox{
      flex-shrink: 0;
      display: flex;
      justify-content: center;
      position: relative;
      background: #fff;
      height: 70px;
      line-height: 70px;
      font-size: 24px;
      .leftBox{
        position: absolute;
        left: 20px;
        display: flex;
        align-items: center;
        .backIcon{
          margin-right: 4px;
          font-size: 26px;
        }
      }
    }
    .content{
      background: #fff;
      margin: 15px;
      padding: 10px 20px 25px 20px;
      .title{
        display: flex;
        align-items: center;
        justify-content: center;
        margin: 10px 0 20px 0;
        position: relative;
        img{
          width: 20px;
          height: 26px;
          margin-right: 10px;
        }
        h3{
          font-size: 25px;
          font-weight: normal;
        }
        .totlaNum{
          position: absolute;
          left: 0px;
        }
        .statusBox{
          position: absolute;
          right: 0;
          color: #999;
          img{
            width: 15px;
            height: 14px;
          }
          .textActive{
            color: #6DD400!important;
          }
        }
      }
      .itemBox{
        display: flex;
        overflow: scroll;
        margin-top: 10px;
        .item{
          margin-right: 25px;
          .dotBox{
            display: flex;
            justify-content: center;
            .dot{
              width: 13px;
              height: 13px;
              // background: #007DBC;
              background: red;
              margin-right: 10px;
              &:last-child{
                margin-right: 0;
              }
            }
            .active{
              background: #12e512;
            }
          }
          .msgBox{
            border: 1px solid #ccc;
            padding: 10px 20px;
            box-sizing: border-box;
            position: relative;
            .msg{
              .msgItem{
                display: flex;
                align-items: center;
                color: #666;
                line-height: 37px;
                font-size: 20px;
                span:first-child{
                  width: 88px;
                }
              }
            }
            .btnBox{
              margin-top: 5px;
              .btn{
                font-size: 24px;
                color: #000!important;
                width: 100%;
                height: 50px;
              }
            }
            .firstStationQty{
              display: flex;
              justify-content: center;
              align-items: center;
              color: #feea27;
              top: 10px;
              background: rgba(0, 125, 188, .7);
              color: #fff;
              position: absolute;
              font-size: 17px;
              padding: 8px;
              left: 0;
            }
            .vanImg{
              position: relative;
              left: 50%;
              transform: translateX(-50%);
            }
          }
          .msgBoxActiveRed{
            border: 4px solid red;
            padding: 6px;
          }
          .msgBoxActive{
            border: 4px solid #007dbc;
            .msgItem{
              color: #000!important;
              span:last-child{
                color: #007DBC!important;
              }
            }
          }
          .msgFive{
            padding: 10px 31px!important;
          }
        }
      }
    }
  }
</style>